package com.woniu.cq.medical.service.impl;

import com.woniu.cq.medical.common.DateUtil;
import com.woniu.cq.medical.common.Result;
import com.woniu.cq.medical.controller.form.AttendanceRecordForm;
import com.woniu.cq.medical.controller.form.PatientWaitForm;
import com.woniu.cq.medical.controller.form.VirtualCallMessageForm;
import com.woniu.cq.medical.dao.*;
import com.woniu.cq.medical.controller.form.DoctorOrDutyForm;
import com.woniu.cq.medical.entity.AttendanceRecord;
import com.woniu.cq.medical.entity.Doctor;
import com.woniu.cq.medical.entity.Patient;
import com.woniu.cq.medical.service.AdministrativeWorkloadAccountService;
import com.woniu.cq.medical.service.DoctorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.cq.medical.service.DutyService;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Lucas
 * @since 2020-09-05
 */
@Service
public class DoctorServiceImpl extends ServiceImpl<DoctorMapper, Doctor> implements DoctorService {
    @Autowired
    private DoctorMapper doctorMapper;
    @Autowired
    private RegisterMapper registerMapper;
    @Autowired
    private PatientMapper patientMapper;
    @Autowired
    private AttendanceRecordMapper attendanceRecordMapper;
    @Autowired
    private AdministrativeWorkloadAccountMapper administrativeWorkloadAccountMapper;
    @Autowired
    private DutyService dutyService;
    @Autowired
    private DutyMapper dutyMapper;

    @Override
    public List<AttendanceRecordForm> showDiagnosisSchedule(Date date) {
        //1、根据时间找出今日值班医生集合
        //2、根据当日值班医生编号找出对就诊记录表查出当前候诊人，已诊人数，候诊人数；
        //3、根据就诊日期，医生编号，查出挂号表中未就诊的患者姓名集合
        List<AttendanceRecordForm> recordFormList = doctorMapper.showDiagnosisSchedule(date);
        for(int i=0;i<recordFormList.size();i++){
            int doctorId = recordFormList.get(i).getDoctorId();
            String status="未就诊";
            List<String> unusedWaitPatientList = registerMapper.queryWaitPatientList(date, doctorId, status,"未过号");
            List<String> passWaitPatientList= registerMapper.queryWaitPatientList(date,doctorId,status,"已过号");
            List<String> waitList =new ArrayList<>();
            for(int j=0;j<unusedWaitPatientList.size();j++){
                waitList.add((j+1)+"、"+unusedWaitPatientList.get(j)+";");
            }
            int size=waitList.size();
            for(int k=0;k<passWaitPatientList.size();k++){
                waitList.add((size+k+1)+"、"+passWaitPatientList.get(k)+";");
            }
            recordFormList.get(i).setWaitPatientList(waitList);
        }
        return recordFormList;
    }

    @Override
    public Doctor doctorLogin(int doctorId, String doctorPassword) throws RuntimeException{
        Doctor doctor = doctorMapper.findByDoctorId(doctorId);
        if(doctor==null){
            throw new RuntimeException("医生工号不存在");
        }
        if(!doctor.getDoctorPassword().equals(doctorPassword)){
            throw new RuntimeException("密码与工号不匹配");
        }
        return doctor;
    }

    /**
    *@Description: 得到等待患者集合
    *@return: 等待就诊患者集合
    */
    @Override
    public List<Patient> getWaitPatientList(int doctorId){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateTime = format.format(new Date());
        List<Patient> waitPatientList=null;
        try {
            Date date = format.parse(dateTime);
            List<Patient> unusedWaitPatientList = registerMapper.getWaitPatientList(date, doctorId, "未就诊", "未过号");
            List<Patient> passWaitPatientList = registerMapper.getWaitPatientList(date, doctorId, "未就诊", "已过号");
            waitPatientList = new ArrayList<>(unusedWaitPatientList);
            waitPatientList.addAll(passWaitPatientList);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return waitPatientList;
    }
    /**
    *@Description: 得到当前就诊患者
    *@return: 当前就诊患者
    */
    @Override
    public PatientWaitForm getCurrPatient(int doctorId) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateTime = format.format(new Date());
        PatientWaitForm patient=null;
        try {
            Date date = format.parse(dateTime);
           patient = registerMapper.getCurrPatient(date, doctorId, "就诊中");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return patient;
    }


    /**
     * 根据科室ID 分别得出医生的名字、职称 以及排班时间
     * @param administrativeId
     * @return
     */
    @Override
    public List<DoctorOrDutyForm> queryAdministrationOrDoctorList(Integer administrativeId) throws ParseException {
        List<Doctor> doctors = doctorMapper.queryAdministrationOrDoctorList(administrativeId);
        List<DoctorOrDutyForm> DoctorOrDutyForms = new ArrayList<>();
        for (Doctor doctor: doctors) {
            DoctorOrDutyForm doctorOrDutyForm = new DoctorOrDutyForm();
            doctorOrDutyForm.setDoctorId(doctor.getDoctorId());
            doctorOrDutyForm.setDoctorName(doctor.getDoctorName());
            doctorOrDutyForm.setDoctorDuty(doctor.getDoctorDuty());
            doctorOrDutyForm.setDoctorRegisterCharge(doctor.getDoctorRegisterCharge());
            List<Date> dates = dutyService.queryDutyDateList(doctor.getDoctorId());
            Map<String, String> dataWeek = DateUtil.getDataWeek(dates);
            doctorOrDutyForm.setDutyTime(dataWeek);
            DoctorOrDutyForms.add(doctorOrDutyForm);
        }
        return DoctorOrDutyForms;
    }

    @Override
    public String getAdministrativeName(int doctorId) {
        return doctorMapper.getAdministrativeName(doctorId);
    }

    @Override
    public void changeRegisterStatusByRegisterId(int registerId,String status) {
        registerMapper.changeRegisterStatusByRegisterId(registerId,status);
    }

    @Override
    public void changeAttendanceRecord(int doctorId,String currPatient) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateTime = format.format(new Date());
        try {
            Date date  = format.parse(dateTime);
            attendanceRecordMapper.changeAttendanceRecord(doctorId,date,currPatient);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void changeAttendanceRecordCheckedCount(int doctorId, String currPatient) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateTime = format.format(new Date());
        try {
            Date date  = format.parse(dateTime);
            attendanceRecordMapper.changeAttendanceRecordCheckedCount(doctorId,date,currPatient);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    @Override
    public int selectPatientCountByStatus(int doctorId, String status) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateTime = format.format(new Date());
        int count=0;
        try {
            Date date  = format.parse(dateTime);
            count=registerMapper.selectPatientCountByStatus(doctorId,date,status);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return count;
    }

    @Override
    public void changeRegisterIsValidByRegisterId(int registerId) {
        String isValid=registerMapper.selectIsValidByRegisterId(registerId);
        if(isValid.equals("未过号")){
            isValid="已过号";
            registerMapper.updateIsValid(registerId,isValid);
        }else if(isValid.equals("已过号")){
            isValid="失约";
            registerMapper.updateIsValid(registerId,isValid);
        }
    }

    @Override
    public VirtualCallMessageForm getVirtualCallMessageForm(int doctorId) {
        VirtualCallMessageForm virtualCallMessageForm = new VirtualCallMessageForm();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateTime = format.format(new Date());
        List<Patient> waitPatientList=null;
        PatientWaitForm patient=null;
        try {
            Date date = format.parse(dateTime);
            List<Patient> unusedWaitPatientList = registerMapper.getWaitPatientList(date, doctorId, "未就诊", "未过号");
            List<Patient> passWaitPatientList = registerMapper.getWaitPatientList(date, doctorId, "未就诊", "已过号");
            waitPatientList = new ArrayList<>(unusedWaitPatientList);
            waitPatientList.addAll(passWaitPatientList);
            virtualCallMessageForm.setWaitPatientList(waitPatientList);
            patient = registerMapper.getCurrPatient(date, doctorId, "就诊中");
            virtualCallMessageForm.setCurrPatient(patient);
            String administrativeName = doctorMapper.getAdministrativeName(doctorId);
            virtualCallMessageForm.setAdministrativeName(administrativeName);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return virtualCallMessageForm;
    }

    @Override
    public Result doctorTreatmentService(int doctorId, String status, String currPatient, int registerId,Doctor doctor) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateTime = format.format(new Date());
        Result result=null;
        int count=0;
        try {
            Date date  = format.parse(dateTime);
            //1、根据医生编号，时间，和就诊状态查询当前医生的就诊中人数
            count=registerMapper.selectPatientCountByStatus(doctorId,date,status);
            if(count==0){
                //2、改变挂号表中的就诊状态，更改为就诊中;
                registerMapper.changeRegisterStatusByRegisterId(registerId,status);
                //3、更改出诊记录表中当前当前患者字段、等待就诊人数-1;
                attendanceRecordMapper.changeAttendanceRecord(doctorId,date,currPatient);
                VirtualCallMessageForm virtualCallMessageForm = getVirtualCallMessageForm(doctorId);
                virtualCallMessageForm.setDoctor(doctor);
                result=Result.success(virtualCallMessageForm);
            }else {
                result=Result.fail("2001","上一位就诊病人还未诊疗结束，请继续为其诊疗！");
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public Result doctorDiagnoseFinishService(int registerId, String status, int doctorId, String currPatient, Doctor doctor) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateTime = format.format(new Date());
        Result result=null;
        try {
            Date date  = format.parse(dateTime);
            registerMapper.changeRegisterStatusByRegisterId(registerId,status);
            attendanceRecordMapper.changeAttendanceRecordCheckedCount(doctorId,date,currPatient);
            //根据科室编号和日期，修改科室工作量统计表中候诊人数（-1）、已诊人数（+1）
            int administrativeId=doctor.getAdministrativeId();
            administrativeWorkloadAccountMapper.updatePatientCount(administrativeId,date);
            VirtualCallMessageForm virtualCallMessageForm = getVirtualCallMessageForm(doctorId);
            virtualCallMessageForm.setDoctor(doctor);
            result=Result.success(virtualCallMessageForm);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public Result doctorPassPatientService(int doctorId, String status, int registerId, Doctor doctor) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateTime = format.format(new Date());
        Result result=null;
        int count=0;
        try {
            Date date  = format.parse(dateTime);
            count=registerMapper.selectPatientCountByStatus(doctorId,date,status);
            if(count==0){
                String isValid=registerMapper.selectIsValidByRegisterId(registerId);
                if(isValid.equals("未过号")){
                    isValid="已过号";
                    registerMapper.updateIsValid(registerId,isValid);
                }else if(isValid.equals("已过号")){
                    isValid="失约";
                    registerMapper.updateIsValid(registerId,isValid);
                    //修改医生出诊表中候诊人数（-1）
                    attendanceRecordMapper.changeAttendanceRecordWaitCheckCount(doctorId,date);
                    //修改科室工作量统计表中候诊人数（-1）
                    int administrativeId=doctor.getAdministrativeId();
                    administrativeWorkloadAccountMapper.updateWaitPatientCount(administrativeId,date);
                }
                VirtualCallMessageForm virtualCallMessageForm = getVirtualCallMessageForm(doctorId);
                virtualCallMessageForm.setDoctor(doctor);
                result=Result.success(virtualCallMessageForm);
            }else {
                result=Result.fail("2001","上一位就诊病人还未诊疗结束，请继续为其诊疗！");
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 根据科室ID查询医师名单
     * @param administrativeId
     * @return
     */
    @Override
    public List<Doctor> queryDoctorList(Integer administrativeId) {

        List<Doctor> doctors = doctorMapper.queryAdministrationOrDoctorList(administrativeId);
        return doctors;
    }

    @Override
    public Doctor userLogin(int doctorId) {
        return doctorMapper.selectById(doctorId);
    }

    @Override
    @Transactional
    public Result addAttendanceRecord(Doctor doctor) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateTime = format.format(new Date());
        Result result=null;
        try {
            Date date = format.parse(dateTime);
            int doctorId = doctor.getDoctorId();
            //1、根据日期和医生编号，查询排班表中该医生今日是否值班
            int dutyCount=dutyMapper.selectDoctorDuty(doctorId,date);
            if(dutyCount==1){
                //2、根据日期和医生编号，查询出诊记录表是否存在
                int count=attendanceRecordMapper.selectAttendanceRecord(doctorId,date);
                if(count==0){
                    //3、根据日期和医生编号，查询出挂号记录表今日已就诊的患者人数
                    String status="已就诊";
                    int checkedCount=registerMapper.selectCheckedCount(doctorId,date,status);
                    //4、根据日期和医生编号，查询出挂号记录表中正在就诊的患者姓名
                    status="就诊中";
                    String currPatientName=registerMapper.selectCurrPatient(doctorId,date,status);
                    //5、根据日期和医生编号，查询出挂号记录表今日未就诊且is_valid!=失约的人数
                    status="未就诊";
                    String isValid="失约";
                    int waitPatientCount=registerMapper.selectWaitPatient(doctorId,date,status,isValid);
                    AttendanceRecord attendanceRecord = new AttendanceRecord();
                    attendanceRecord.setDoctorId(doctorId);
                    attendanceRecord.setDoctorName(doctor.getDoctorName());
                    attendanceRecord.setDoctorDuty(doctor.getDoctorDuty());
                    attendanceRecord.setCheckedCount(checkedCount);
                    attendanceRecord.setWaitCheckCount(waitPatientCount);
                    attendanceRecord.setCurrPatient(currPatientName);
                    attendanceRecord.setAttendanceDate(date);
                    attendanceRecordMapper.insert(attendanceRecord);
                    result=Result.success();
                }else {
                    result=Result.fail("3001","今日已增加出诊记录表，请不要重复创建!!!");
                }
            }else {
                result=Result.fail("3002","今日您没有排班，请不要创建出诊记录!!!");
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return result;
    }
}
